是一家專注人工智慧與自然語言處理(NLP)公司,最著名產品是 Transformers
一個開源的機器學習框架,支援使用 BERT、GPT、T5 等各種大型語言模型(LLM)
PyTorch、TensorFlow、JAX
三大框架BERT
(Bidirectional Encoder Representations from Transformers)GPT-2 / GPT-3 / GPT-4
T5
(Text-to-Text Transfer Transformer)BLOOM
(開源 GPT 類似模型)LLaMA
(Meta 開發的語言模型)pip install transformers
from transformers import pipeline
generator = pipeline("text-generation", model="gpt2")
print(generator("Once upon a time", max_length=50))
提供數千個開源資料集,支援 NLP、CV、語音處理並可直接加載並用於模型訓練
pip install datasets
from datasets import load_dataset
dataset = load_dataset("imdb")
print(dataset["train"][0])
全球最大開源AI模型平台搜尋並下載各類LLM
bert-base-uncased
gpt-neo-2.7B
bigscience/bloom
meta-llama/Llama-2-7b
from transformers import AutoModel
model = AutoModel.from_pretrained("bert-base-uncased")
提供雲端推論 API,無需本地執行模型,適合快速構建應用,尤其在資源受限環境下
from transformers import pipeline
classifier = pipeline("sentiment-analysis", model="distilbert-base-uncased-finetuned-sst-2-english")
print(classifier("I love Hugging Face!"))
開源革命
:推動 LLM 民主化,讓每個人都能接觸最先進的 AI 模型企業應用廣泛
:Microsoft、Meta 等科技巨頭皆採用其工具責任性AI
:推動檢測與降低模型偏見與幻覺的工具(例如:transformers-interpret)✅ 研究人員 測試、微調與比較各種 NLP/LLM 模型
✅ 開發者 快速構建 NLP 應用(如聊天機器人、分析工具)
✅ 企業 部署 AI 解決方案,提高自動化與效率
transformers 函式庫提供了一個非常方便的高階 API 叫做 pipeline,它可以讓我們用幾行程式碼就完成一個完整的 AI 推理流程(從前處理到模型預測再到後處理)
安裝必要的函式庫
首先,已安裝 transformers、PyTorch (或 TensorFlow/JAX) 以及 Pillow (用於圖片處理)
pip install transformers torch pillow
這是最常見的電腦視覺任務:判斷一張圖片屬於哪個類別
任務情境:我們有一張貓的圖片,想讓 AI 告訴我們這是一隻什麼品種的貓
# 匯入必要的函式庫
from transformers import pipeline
from PIL import Image
import requests # 用來從網路下載圖片
# 步驟 1: 初始化圖片分類的 pipeline
# 'image-classification' 是任務名稱。Hugging Face 會自動下載預設的模型。
# 這裡會使用 'google/vit-base-patch16-224',一個強大的 Vision Transformer 模型。
classifier = pipeline("image-classification")
# 步驟 2: 準備圖片
# 我們從網路上找一張貓的圖片 URL
url = "http://images.cocodataset.org/val2017/000000039769.jpg"
# 使用 requests 下載圖片內容,並用 PIL.Image 開啟
image = Image.open(requests.get(url, stream=True).raw)
# 顯示圖片 (在 Jupyter Notebook 或類似環境中)
# image.show() # 如果在本機端執行,會開啟圖片瀏覽器
# 步驟 3: 進行分類預測
# 直接將圖片物件傳遞給 classifier
results = classifier(image)
# 步驟 4: 輸出結果
# 結果會是一個列表,包含多個可能的類別及其信心分數
print("圖片分類結果:")
for result in results:
# 'score' 是信心度,'label' 是預測的標籤
print(f"標籤: {result['label']}, 信心度: {result['score']:.4f}")
程式碼解說:
pipeline("image-classification") 會自動處理所有繁瑣的步驟:圖片的尺寸調整、正規化、轉換為模型需要Tensor格式等等只需要提供一個 PIL.Image 物件,pipeline 就會回傳一個包含預測標籤 (label) 和信心度 (score) 的 Python 字典列表。輸出可能會包含 "Egyptian cat"、"tabby, tabby cat" 等,展示了模型對貓品種的精確識別能力
這個任務不只要分類,還要找出圖片中所有物件的位置(以邊界框 Bounding Box 表示)
任務情境: 辨識出前一張圖片中的所有貓和遙控器,並框出它們的位置
# 匯入必要的函式庫
from transformers import pipeline
from PIL import Image, ImageDraw, ImageFont
import requests
# 步驟 1: 初始化物件偵測的 pipeline
# 預設會使用 'facebook/detr-resnet-50' 模型
object_detector = pipeline("object-detection")
# 步驟 2: 準備圖片 (使用同一張貓的圖片)
url = "http://images.cocodataset.org/val2017/000000039769.jpg"
image = Image.open(requests.get(url, stream=True).raw)
# 步驟 3: 進行物件偵測
results = object_detector(image)
# 步驟 4: 處理並視覺化結果
print("物件偵測結果:")
draw = ImageDraw.Draw(image) # 建立一個可以在圖片上繪圖的物件
for detection in results:
label = detection["label"]
score = detection["score"]
box = detection["box"]
print(f"偵測到物件: {label}, 信心度: {score:.4f}, 位置: {box}")
# 在圖片上畫出邊界框
# box 格式為 {'xmin': x, 'ymin': y, 'xmax': x, 'ymax': y}
rect = [box['xmin'], box['ymin'], box['xmax'], box['ymax']]
draw.rectangle(rect, outline="red", width=3)
# 在框的上方寫上標籤和信心度
text = f"{label} ({score:.2f})"
draw.text((box['xmin'], box['ymin'] - 10), text, fill="red")
# 顯示標記後的圖片
# image.show()
# 若在 Jupyter Notebook 中,可以直接顯示 image
image
程式碼解說
pipeline("object-detection") 使用的是 DETR (DEtection TRansformer) 模型,它能直接預測出一組物件的類別和邊界框,回傳的結果中,box 字典詳細定義了每個偵測到物件的左上角和右下角座標,我們使用 PIL 的 ImageDraw 模組,將這些邊界框和標籤直接畫在原始圖片上,實現結果的視覺化
diffusers 是 Hugging Face 專為擴散模型(Stable Diffusion)打造的函式庫,讓「以文生圖」變得極為簡單
安裝必要的函式庫
diffusers 需要額外安裝。為了獲得更好的效能,建議在有 NVIDIA GPU 的環境下執行,並安裝 accelerate
pip install diffusers transformers accelerate torch
任務情境: 我們想生成一張「一隻太空貓在畢卡索風格的畫布上」的圖片
# 匯入必要的函式庫
import torch
from diffusers import DiffusionPipeline
# 步驟 1: 載入預訓練的擴散模型 pipeline
# 'runwayml/stable-diffusion-v1-5' 是一個經典且高效的 Stable Diffusion 模型
# torch_dtype=torch.float16 是為了在使用 GPU 時節省記憶體並加速,如果沒有 GPU 則不需要此參數
# use_safetensors=True 是為了更安全地載入模型權重
pipe = DiffusionPipeline.from_pretrained(
"runwayml/stable-diffusion-v1-5",
torch_dtype=torch.float16,
use_safetensors=True
)
# 步驟 2: 將 pipeline 移至 GPU (如果可用)
# 這是發揮模型效能的關鍵步驟
if torch.cuda.is_available():
pipe = pipe.to("cuda")
else:
print("未偵測到 CUDA GPU,將使用 CPU 進行計算 (速度會非常慢)。")
# 步驟 3: 定義你的「咒語」(Prompt)
# Prompt 的描述越詳細、越生動,生成的圖片品質通常越好
prompt = "An image of a squirrel in Picasso style" # 官方範例:畢卡索風格的松鼠
# 我們改成中文使用者更感興趣的 prompt
prompt_zh = "一隻穿著太空衣的可愛貓咪,坐在月球上,望著地球,數位藝術風格"
# 注意: 大部分開源模型對英文 Prompt 的理解比中文好。
# 如果想用中文,最好先翻譯成英文。這裡我們直接用英文 prompt 進行示範。
prompt_en = "A cute cat in an astronaut suit, sitting on the moon and looking at the earth, digital art style"
# 步驟 4: 生成圖片
# 傳入 prompt,函式庫會執行去噪過程並生成圖片
# 為了讓每次生成的結果可重現,我們可以設定一個隨機種子 (generator)
generator = torch.Generator("cuda").manual_seed(0) if torch.cuda.is_available() else None
image = pipe(prompt_en, generator=generator).images[0]
# 步驟 5: 顯示或儲存圖片
print("圖片生成成功!")
# image.show() # 在本機顯示圖片
# image.save("astronaut_cat.png") # 儲存圖片
# 在 Jupyter Notebook 中可以直接顯示
image
程式碼解說:
DiffusionPipeline.from_pretrained(...) 會從 Hugging Face Hub 下載指定的 Stable Diffusion 模型所需的所有元件(U-Net、VAE、Tokenizer 等).to("cuda") 是 PyTorch 的標準做法,將模型和計算轉移到 GPU 上,這對圖片生成任務至關重要,否則在 CPU 上可能需要數十分鐘甚至更久。核心就是 pipe(prompt) 這一行,它封裝了極其複雜的擴散模型推理過程。images[0] 是因為 pipe 可能一次生成多張圖片,我們取第一張。generator 的使用是個好習慣,它能確保你在使用相同參數時,每次都能得到完全一樣的生成結果,方便除錯和比較。
Hugging Face 是 NLP 和 LLM 領域的核心平台,無論是模型訓練、應用開發還是部署上線,都能透過其工具快速實現